package cn.shop.crontab.task;

import cn.shop.crontab.entity.FrozenAmount;
import cn.shop.transcation.order.entity.OrderFrozenAmount;
import cn.shop.transcation.order.mapper.OrderFrozenAmountMapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author : 李一涵
 * @date : Created in 2022-2-27 10:55
 * @description :
 */
//@Service
public class OrderFrozenAmountTask {

	/*private final static String SELECT = "select id, user_id, amount, dead_time from order_frozen_amount where deleted = false order by dead_time asc";

	private final static String DELETE = "update order_frozen_amount set update_time = ?, deleted = ? where id = ?";

	private final static String UPDATE_USER = "update front_user set income = income + ? where id = ?";

	private final static String INSERT_INBOX = "insert into inbox(id, content, create_time, create_id) values(?, ?, ?, ?)";

	@Resource
	private JdbcTemplate jdbcTemplate;
	@Resource
	private OrderFrozenAmountMapper mapper;

	@Scheduled(cron = "0/30 * * * * ?")
	@Transactional(rollbackFor = Exception.class)
	public void checkAmount() {
		//List<FrozenAmount> list = jdbcTemplate.query(SELECT, new BeanPropertyRowMapper<>(FrozenAmount.class));
		List<OrderFrozenAmount> list = mapper.selectList(Wrappers.<OrderFrozenAmount>lambdaQuery()
				.orderByAsc(OrderFrozenAmount::getDeadTime));
		if (list.isEmpty()) {
			return;
		}
		LocalDateTime now = LocalDateTime.now();
		for (OrderFrozenAmount frozenAmount : list) {
			if (now.isBefore(frozenAmount.getDeadTime())) {
				continue;
			}
			int count = jdbcTemplate.update(UPDATE_USER, frozenAmount.getAmount(), frozenAmount.getUserId());
			if (count > 0) {
				jdbcTemplate.update(DELETE, LocalDateTime.now(), true, frozenAmount.getId());
				jdbcTemplate.update(INSERT_INBOX, IdWorker.getId(), "您的订单收益已解禁", LocalDateTime.now(), 0);
			}
		}
	}*/

}
